package com.atguigu.tingshu.search.receiver;

import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.search.service.SearchService;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * projectName: com.atguigu.tingshu.search.receiver
 *
 * @author: 吴振鹏
 * description:
 * time: 2025/9/4 19:54
 */
@Component
@Slf4j
public class SearchReceiver {

    @Autowired
    private SearchService searchService;

    /**
    * 监听上架专辑消息
    * @param albumId
    */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_UPPER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_UPPER
    ))
    public void albumUpper(Long albumId, Message message, Channel channel) {
        //监听专辑上架
        System.out.println("上架专辑：" + albumId);

        try {
            if(null != albumId){
                searchService.upperAlbum(albumId);
            }
        } catch (Exception e) {
            log.error("上架专辑失败：" + e.getMessage(), e);
        }

        //确认消息,手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息确认失败：" + e.getMessage(), e);
        }

    }




    /**
     * 监听下架专辑消息
     * @param albumId
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_ALBUM_LOWER, durable = "true", autoDelete = "false"),
            exchange = @Exchange(value = MqConst.EXCHANGE_ALBUM),
            key = MqConst.ROUTING_ALBUM_LOWER
    ))
    public void albumLower(Long albumId, Message message, Channel channel) {
        //监听专辑下架
        System.out.println("下架专辑：" + albumId);

        try {
            if(null != albumId){
                searchService.lowerAlbum(albumId);
            }
        } catch (Exception e) {
            log.error("下架专辑失败：" + e.getMessage(), e);
        }

        //确认消息,手动确认消息
        try {
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        } catch (Exception e) {
            log.error("消息确认失败：" + e.getMessage(), e);
        }

    }



}
